/**
 * Copyright (C), 2020-2020, 软件公司
 * FileName: DealQueue.java
 * Author:   cakin
 * Date:     2020/5/9
 * Description: 死信队列演示
 */
package com.rabbitmq.dlx;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.MessageProperties;
import com.rabbitmq.util.ConnectionUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

import static com.rabbitmq.common.Constant.NUM10000;

/**
 * 死信队列（路由键为rk的消息过期后被放置到死信队列）
 */
@Slf4j
public class DealQueue {


    public static void main( String[] args ) {
        try {
            Connection connection = ConnectionUtils.getConnection();
            Channel channel = connection.createChannel();
            // 声明死信交换器和正常交换器
            channel.exchangeDeclare("exchange.dlx", "direct", true, false, null);
            channel.exchangeDeclare("exchange.normal", "fanout", true, false, null);

            // 正常队列的声明和绑定
            Map<String, Object> arg = new HashMap<String, Object>();
            arg.put("x-message-ttl", NUM10000);
            arg.put("x-dead-letter-exchange", "exchange.dlx");
            channel.queueDeclare("queue.normal", false, false, false, arg);
            channel.queueBind("queue.normal", "exchange.normal", "");
            // 死信队列的声明和绑定
            channel.queueDeclare("queue.dlx", false, false, false, null);
            channel.queueBind("queue.dlx", "exchange.dlx", "rk");

            // 发送消息
            String message = "delay message !";
            channel.basicPublish("exchange.normal", "rk", false,
                    MessageProperties.PERSISTENT_TEXT_PLAIN,
                    message.getBytes());
            ConnectionUtils.close(channel, connection);
        } catch (IOException e) {
            log.info("catch IOException");
        } catch (TimeoutException e) {
            log.info("catch TimeoutException");
        }
    }
}
